package com.yx.gsyd.controller.app;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.gsyd.comm.ResultEnum;
import com.yx.gsyd.entity.SysManager;
import com.yx.gsyd.entity.TaskList;
import com.yx.gsyd.entity.req.TaskListReq;
import com.yx.gsyd.entity.search.MainChartSearch;
import com.yx.gsyd.entity.search.TaskListSearch;
import com.yx.gsyd.entity.view.MainChartView;
import com.yx.gsyd.entity.view.MainCountView;
import com.yx.gsyd.exception.MyException;
import com.yx.gsyd.qpage.QPage;
import com.yx.gsyd.redis.RedisService;
import com.yx.gsyd.satoken.StpUserUtil;
import com.yx.gsyd.service.IMainCountService;
import com.yx.gsyd.service.ISysManagerService;
import com.yx.gsyd.service.ITaskListService;
import com.yx.gsyd.sms.AliSMS;
import com.yx.gsyd.util.DateUtils;
import com.yx.gsyd.util.IdentityUtil;
import com.yx.gsyd.util.ResultView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-29
 */
@Slf4j
@RestController
@RequestMapping("/api/front/task-list")
public class AppTaskListController {

    @Autowired
    private ITaskListService iTaskListService;

    @Autowired
    private AliSMS aliSMS;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IMainCountService iMainCountService;

    @Autowired
    private ISysManagerService iSysManagerService;


    /**
     * 发送验证码
     * @param sjhm
     * @return
     */
    @PostMapping("/sendPhone")
    public ResultView sendPhone(String sjhm,String gsmc) {
        if(StringUtils.isEmpty(sjhm)){
            throw new MyException(ResultEnum.CODE_2,"手机号码不能为空");
        }
        Map<String,Object> objectMap=new HashMap<>();
        String code= IdentityUtil.getRandomNum(6);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        if(this.aliSMS.sendSms(sjhm,jsonObject.toJSONString(),"SMS_469065639")){
            //存入验证码
            redisService.set(sjhm,code,300);
            objectMap.put("code",1);
            objectMap.put("data","");
            return ResultView.ok(objectMap);
        }
        /*if(StringUtils.isEmpty(gsmc)){
            throw new MyException(ResultEnum.CODE_2,"公司名称不能为空");
        }
        //首先验证当前企业是否已经提交过
        QueryWrapper<TaskList> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("sjhm",sjhm);
        queryWrapper.eq("gsmc",gsmc);
        TaskList taskList=this.iTaskListService.getOne(queryWrapper);
        if(taskList!=null){
            objectMap.put("code",2);
            objectMap.put("data",taskList);
            return ResultView.ok(objectMap);
        }else{
            String code= IdentityUtil.getRandomNum(6);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", code);
            if(this.aliSMS.sendSms(sjhm,jsonObject.toJSONString(),"SMS_469065639")){
                //存入验证码
                redisService.set(sjhm,code,300);
                objectMap.put("code",1);
                objectMap.put("data","");
                return ResultView.ok(objectMap);
            }
        }*/
        return ResultView.error("系统短信通道异常");
    }


    /**
     * 检测当前手机和公司名称是否存着系统
     * @param sjhm
     * @return
     */
    @PostMapping("/exitData")
    public ResultView exitData(String sjhm,String gsmc) {
        if(StringUtils.isEmpty(gsmc)){
            throw new MyException(ResultEnum.CODE_2,"公司名称不能为空");
        }
        if(StringUtils.isEmpty(sjhm)){
            throw new MyException(ResultEnum.CODE_2,"手机号码不能为空");
        }
        Map<String,Object> objectMap=new HashMap<>();
        //首先验证当前企业是否已经提交过
        QueryWrapper<TaskList> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("sjhm",sjhm);
        queryWrapper.eq("gsmc",gsmc);
        TaskList taskList=this.iTaskListService.getOne(queryWrapper);
        if(taskList!=null){
            objectMap.put("code",2);
            objectMap.put("data",taskList);
            return ResultView.ok(objectMap);
        }else{
            objectMap.put("code",1);
            objectMap.put("data","");
            return ResultView.ok(objectMap);
        }
    }

    /**
     * 提交验证码
     * @param taskList
     * @return
     */
    @PostMapping("/sendFirtst")
    public ResultView sendFirtst(TaskListReq taskList) {
        if(StringUtils.isEmpty(taskList.getCode())){
            throw new MyException(ResultEnum.CODE_2,"验证码不能为空");
        }
        if(!redisService.hasKey(taskList.getSjhm())){
            throw new MyException(ResultEnum.CODE_2,"验证码已失效，请重新获取");
        }
        String code=redisService.get(taskList.getSjhm()).toString();
        if(!taskList.getCode().equals(code)){
            throw new MyException(ResultEnum.CODE_2,"验证码不匹配，请重新输入");
        }
        return ResultView.ok(taskList);
    }



    /**
     * 提交申请
     * @param taskList
     * @return
     */
    @PostMapping("/createTask")
    public ResultView createTask(TaskList taskList) {
        taskList.setUserId(StpUserUtil.getLoginIdAsInt());
        return this.iTaskListService.createTask(taskList);
    }


    /**
     * 转换经纬度
     * @param location
     * @return
     */
    @GetMapping("/getMapTask")
    public ResultView getMapTask(String location) {
        String data=HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1/?location="+location+"&key=W23BZ-GTX3L-PUEPZ-MRZ5O-VUQPT-72FN3&get_poi=1");
        return ResultView.ok(data);
    }


    /**
     * 营业执照识别接口
     * @return
     */
    @PostMapping("/cardCheck")
    public ResultView cardCheck(@RequestParam("file") MultipartFile file) throws IOException {
        String bdToken="";
        if(redisService.hasKey("bdToken")){
            bdToken=redisService.get("bdToken").toString();
        }else{
            String result = HttpUtil.createRequest(Method.POST,"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=D8e25KlPK3UgimhtTeTFVetB&client_secret=QH9fh6pEsGvC9rDTy8M7VzGFP5SYSLqH")
                    .header("Content-Type", "application/json;charset=utf-8")
                    .timeout(3000)
                    .execute()
                    .body();
            log.info(">>>>>>获取第三方百度token接口参数>>>>>>>>>>{"+result.toString()+"}");
            JSONObject json=JSON.parseObject(result);
            bdToken=json.getString("access_token");
            redisService.set("bdToken",bdToken,2500000);
        }
        byte[] imageBytes = file.getBytes();
        Map param =new HashMap();
        param.put("image", Base64.getEncoder().encodeToString(imageBytes));
        param.put("access_token",bdToken);
        String data = HttpUtil.post("https://aip.baidubce.com/rest/2.0/ocr/v1/business_license", param);
        log.info(">>>>>>第三方识别身营业执照返回参数>>>>>>>>>>{"+data+"}");
        return ResultView.ok(data);
    }



    /**
     * 统计首页数据图
     * @return
     */
    @GetMapping("/getMainCount")
    public ResultView getMainCount() {
        String managerId=StpUserUtil.getLoginIdAsString();
        SysManager sysManager=this.iSysManagerService.getById(managerId);
        TaskListSearch obj=new TaskListSearch();
        if(sysManager.getMType()==1||sysManager.getMType()==3){
            System.out.println("全部权限");
            obj.setAdminId("all");
        }else{
            if(sysManager.getMType()==2){
                obj.setFwzxzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==4){
                obj.setJhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==5){
                obj.setYhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==6){
                SysManager parent=this.iSysManagerService.getById(sysManager.getParentManagerId());
                if(parent.getMType()==2){
                    obj.setFwzxygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==4){
                    obj.setJhtdygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==5){
                    obj.setYhtdygManagerId(sysManager.getManagerId());
                }
            }
        }
        MainCountView mainCountView=this.iMainCountService.getMainCount(obj);
        return ResultView.ok(mainCountView);
    }



    /**
     * 统计首页Echart数据图
     * @return
     */
    @GetMapping("/getEchartCount")
    public ResultView getEchartCount() throws ParseException {
        String managerId=StpUserUtil.getLoginIdAsString();
        SysManager sysManager=this.iSysManagerService.getById(managerId);
        TaskListSearch obj=new TaskListSearch();
        if(sysManager.getMType()==1||sysManager.getMType()==3){
            System.out.println("全部权限");
            obj.setAdminId("all");
        }else{
            if(sysManager.getMType()==2){
                obj.setFwzxzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==4){
                obj.setJhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==5){
                obj.setYhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==6){
                SysManager parent=this.iSysManagerService.getById(sysManager.getParentManagerId());
                if(parent.getMType()==2){
                    obj.setFwzxygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==4){
                    obj.setJhtdygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==5){
                    obj.setYhtdygManagerId(sysManager.getManagerId());
                }
            }
        }
        List<MainChartView> mainChartViewList=new ArrayList<>();
        MainChartView mainChartView=null;
        MainChartSearch mainChartSearch=null;
        //week 周期  0本周，-1上周，-2上上周，1下周，2下下周
        //本周
        String[] bzList= DateUtils.getWeekStartAndEnd(0);
        List<String> bzstringList=DateUtils.getDaysBetweenTwoDays(bzList[0],bzList[1]);
        //上周
        String[] szList= DateUtils.getWeekStartAndEnd(-1);
        List<String> szstringList=DateUtils.getDaysBetweenTwoDays(szList[0],szList[1]);
        for(int i=0;i<=6;i++){
            obj.setBzDay(bzstringList.get(i));
            obj.setSzDay(szstringList.get(i));
            mainChartView=this.iMainCountService.getEchartCount(obj);
            mainChartView.setWeek(DateUtils.getWeekOfDate(DateUtils.stringToDate(bzstringList.get(i))));
            mainChartViewList.add(mainChartView);
        }
        return ResultView.ok(mainChartViewList);
    }


    /**
     * 列表分页
     * @param obj
     * @return
     */
    @GetMapping("/getPageList")
    public ResultView getPageList(QPage qPage, TaskListSearch obj) {
        SysManager sysManager=this.iSysManagerService.getById(StpUserUtil.getLoginIdAsString());
        //账号类型1.管理员，2.服务中心员工，3数据团队，4.交互团队，5.银行团队6.员工
        if(sysManager.getMType()==1||sysManager.getMType()==3){
            System.out.println("全部权限");
        }else{
            if(sysManager.getMType()==2){
                obj.setFwzxzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==4){
                obj.setJhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==5){
                obj.setYhtdzrManagerId(sysManager.getManagerId());
            }
            if(sysManager.getMType()==6){
                SysManager parent=this.iSysManagerService.getById(sysManager.getParentManagerId());
                if(parent.getMType()==2){
                    obj.setFwzxygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==4){
                    obj.setJhtdygManagerId(sysManager.getManagerId());
                }
                if(parent.getMType()==5){
                    obj.setYhtdygManagerId(sysManager.getManagerId());
                }
            }
        }
        return this.iTaskListService.getPageList(qPage,obj);
    }


    /**
     * 详情
     * @param taskId
     * @return
     */
    @GetMapping("/getListId")
    public ResultView getListId(String taskId) {
        return this.iTaskListService.getListId(taskId);
    }



}
